#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :wx_search_book.py
# @Time      :2023/10/17 
# @Author    :CL
# @email     :1037654919@qq.com
import json
import requests
from retrying import retry

from get_book_info import get_book_info, parse_search_book_info
from get_chapter_num import get_chapter_num
from get_new_cookies import get_new_cookise
from utils import mongo_manager
book_id = mongo_manager('book_id',db = 'wx_read')


@retry(stop_max_attempt_number=5)
def search_book(kw="毛泽东选集",):
    headers = {
        "authority": "weread.qq.com",
        "accept": "application/json, text/plain, */*",
        "accept-language": "zh-CN,zh;q=0.9",
        "referer": "https://weread.qq.com/",
        "sec-ch-ua": "\"Chromium\";v=\"116\", \"Not)A;Brand\";v=\"24\", \"Google Chrome\";v=\"116\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "\"Linux\"",
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-origin",
        "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36"
    }
    # cookies = {
    #     "wr_fp": "1600462502",
    #     "wr_gid": "247667256",
    #     "wr_theme": "white",
    #     "wr_vid": "342130397",
    #     "wr_pf": "0",
    #     "wr_rt": "web%40U47CA31vGHyU_~uO7ef_AL",
    #     "wr_localvid": "dae32b70814647edddae820",
    #     "wr_name": "%E8%90%A7%E7%9F%B3%E5%AD%90",
    #     "wr_avatar": "https%3A%2F%2Fres.weread.qq.com%2Fwravatar%2FWV0025-~CWxfQNwWz94YXURCFRNud4%2F0",
    #     "wr_gender": "1",
    #     "wxuin": "1023513331",
    #     "wr_skey": "_bvxvwGx"
    # }
    url = "https://weread.qq.com/web/search/search_suggest"
    params = {
        "keyword": kw,
        "count": "40"
    }
    response = requests.get(url, headers=headers, cookies=cookies, params=params)

    # print(response.text)
    # print(response)
    if response.status_code == 200:
        json_data = json.loads(response.text)
        records = json_data["records"]

        return records
    else:
        cookies = get_new_cookise()
        raise 'search not get data '
def save_search_records(records):
    for record in records:
        if 'bookId' in record:
            # print(book_id.not_exist({"_id": record["bookId"]}))
            if book_id.not_exist({"_id": record["bookId"]}):
                reslut = {}
                reslut['bookId'] = record['bookId']
                reslut['title'] = record['word']
                reslut["_id"] = reslut['bookId']
                try:
                    reslut["chapterInfos"] = get_chapter_num(reslut['bookId'])
                    chapter_num =[]
                    for chapter in reslut["chapterInfos"]:
                        if chapter["price"] == 0 or chapter["price"] == -1:
                            chapter_num.append(chapter["chapterUid"])
                    reslut["chapter_num"] = chapter_num
                    res = get_book_info(reslut['bookId'])
                    reslut.update(parse_search_book_info(res))
                except BaseException as e:
                    print(e)
                try:
                    book_id.insertOne(reslut)
                except BaseException as e:
                    print(e)
                    book_id.updateOne({'_id': reslut['_id']}, reslut)


if __name__ =="__main__":
    print()
    cookies = get_new_cookise()
    print(records := search_book())
    # save_search_records(records)
